using System;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using ChatSocketService;
using SmartBoard.Core.Login;
using SmartBoard.Core.Networking;

namespace SmartBoard.Server
{
    public class ChatSocketService : BaseSocketService
    {

        #region Fields

        private ReaderWriterLock FUsersSync;
        private Dictionary<long, ISocketConnection> FUsers;

        #endregion

        #region Constructor

        public ChatSocketService()
        {
            FUsersSync = new ReaderWriterLock();
            FUsers = new Dictionary<long, ISocketConnection>(100);
        }

        #endregion

        #region Methods

        
        #region OnConnected

        public override void OnConnected(ConnectionEventArgs e)
        {

            StringBuilder s = new StringBuilder();

            s.Append("\r\n------------------------------------------------\r\n");
            s.Append("New Client\r\n");
            s.Append(" Connection Id " + e.Connection.ConnectionId + "\r\n");
            s.Append(" Ip Address " + e.Connection.RemoteEndPoint.Address + "\r\n");
            s.Append(" Tcp Port " + e.Connection.RemoteEndPoint.Port + "\r\n");
            
            Console.WriteLine(s.ToString());
            s.Length = 0;
            
            e.Connection.UserData = new ConnectionData(ConnectionState.Connected);
            e.Connection.BeginReceive();
            
        }

        #endregion

        #region OnSent

        public override void OnSent(MessageEventArgs e)
        {

            //if (!e.SentByServer)
            //{
            //    e.Connection.BeginReceive();
            //}

        }

        #endregion

        #region OnReceived

        public override void OnReceived(MessageEventArgs e)
        {

            ChatMessage msg = MessageSerializer.DeserializeMessage(e.Buffer);

            switch (msg.MessageType)
            {

                case MessageType.Login:

                    ((ConnectionData)e.Connection.UserData).ConnectionState = ConnectionState.Authenticated;
                    ((ConnectionData)e.Connection.UserData).UserName = msg.UserInfo[0].UserName;

                    msg.UserInfo[0].UserId = e.Connection.ConnectionId;
                    e.Connection.BeginSend(MessageSerializer.SerializeMessage(msg));
                    
                    msg.MessageType = MessageType.Authenticated;
                    e.Connection.AsServerConnection().BeginSendToAll(MessageSerializer.SerializeMessage(msg), false);
                    
                    ISocketConnection[] cnns = e.Connection.AsServerConnection().GetConnections();
                    
                    if ( (cnns != null) && (cnns.Length > 0) )
                    {
                        
                        bool send = false;
                        
                        msg.MessageType = MessageType.Hello;
                        msg.UserInfo = new UserInfo[cnns.Length];
                        
                        for (int i = 0; i < cnns.Length; i++)
                        {
                            
                            if (cnns[i] != e.Connection)
                            {
                                msg.UserInfo[i].UserName = ((ConnectionData)cnns[i].UserData).UserName;
                                msg.UserInfo[i].UserId = cnns[i].ConnectionId;
                                send = true;
                            }
                            
                        }

                        if (send)
                        {
                            e.Connection.AsServerConnection().BeginSend(MessageSerializer.SerializeMessage(msg));
                        }
                        
                    }                    
                    
                    break;

                case MessageType.Message:

                    e.Connection.AsServerConnection().BeginSendToAll(e.Buffer, false);

                    break;
                    
                    
                case MessageType.Logout:

                    e.Connection.AsServerConnection().BeginSendToAll(MessageSerializer.SerializeMessage(msg), false);
                    break;    
                
            }

            e.Connection.BeginReceive();

        }

        #endregion

        #region OnDisconnected

        public override void OnDisconnected(ConnectionEventArgs e)
        {

            StringBuilder s = new StringBuilder();

            s.Append("------------------------------------------------" + "\r\n");
            s.Append("Client Disconnected\r\n");
            s.Append(" Connection Id " + e.Connection.ConnectionId + "\r\n");
            
            e.Connection.UserData = null;
            
            Console.WriteLine(s.ToString());
            
            s.Length = 0;


        }

        #endregion

        #region OnException

        public override void OnException(ExceptionEventArgs e)
        {
            e.Connection.BeginDisconnect();
        }

        #endregion

        #endregion

    }
}